import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:google_fonts/google_fonts.dart';
import '../constants/app_colors.dart';
import 'package:heroicons/heroicons.dart';
import '../models/thought_record.dart';
import '../models/database_helper.dart';
import 'new_thought_screen.dart';
import 'thought_detail_screen.dart';
import 'home_screen.dart';

class ThoughtReshapingScreen extends StatefulWidget {
  const ThoughtReshapingScreen({Key? key}) : super(key: key);

  @override
  State<ThoughtReshapingScreen> createState() => _ThoughtReshapingScreenState();
}

class _ThoughtReshapingScreenState extends State<ThoughtReshapingScreen> {
  List<ThoughtRecord> _thoughts = [];
  bool _isLoading = true;

  @override
  void initState() {
    super.initState();
    _loadThoughts();
  }

  Future<void> _loadThoughts() async {
    try {
      final thoughts = await DatabaseHelper.instance.getAllThoughtRecords();
      setState(() {
        _thoughts = thoughts;
        _isLoading = false;
      });
    } catch (e) {
      if (!mounted) return;
      ScaffoldMessenger.of(context).showSnackBar(
        SnackBar(content: Text('加载记录失败: ${e.toString()}')),
      );
      setState(() {
        _isLoading = false;
      });
    }
  }

  Widget _buildThoughtCard(ThoughtRecord thought) {
    final labelColors = {
      '非黑即白': Colors.red[300],
      '以偏概全': Colors.blue[300],
      '心理过滤': Colors.green[300],
      '否定正面思维': Colors.purple[300],
      '跳跃式结论': Colors.orange[300],
      '情绪化推理': Colors.teal[300],
      '应该陈述': Colors.pink[300],
      '贴标签': Colors.indigo[300],
      '个人化': Colors.amber[300],
      '放大与缩小': Colors.cyan[300],
    };

    return GestureDetector(
      onTap: () {
        Navigator.pushReplacement(
          context,
          MaterialPageRoute(
            builder: (context) => ThoughtDetailScreen(thoughtRecord: thought),
          ),
        );
      },
      onLongPress: () async {
        // 触发震动反馈
        HapticFeedback.heavyImpact();
        
        final confirm = await showDialog<bool>(
          context: context,
          builder: (context) => AlertDialog(
            title: Text(
              '确认删除',
              style: GoogleFonts.zcoolKuaiLe(
                fontSize: 20,
                fontWeight: FontWeight.bold,
              ),
            ),
            content: Text(
              '确定要删除这条想法记录吗？此操作不可恢复。',
              style: GoogleFonts.zcoolKuaiLe(
                fontSize: 16,
                color: AppColors.textPrimary,
              ),
            ),
            actions: [
              TextButton(
                onPressed: () => Navigator.of(context).pop(false),
                child: Text(
                  '取消',
                  style: GoogleFonts.zcoolKuaiLe(
                    fontSize: 16,
                    color: Colors.grey,
                  ),
                ),
              ),
              TextButton(
                onPressed: () => Navigator.of(context).pop(true),
                child: Text(
                  '删除',
                  style: GoogleFonts.zcoolKuaiLe(
                    fontSize: 16,
                    color: Colors.red,
                  ),
                ),
              ),
            ],
          ),
        );

        if (confirm == true) {
          try {
            await DatabaseHelper.instance.deleteThoughtRecord(thought.id!);
            if (!mounted) return;
            _loadThoughts();
            ScaffoldMessenger.of(context).showSnackBar(
              const SnackBar(content: Text('删除成功')),
            );
          } catch (e) {
            if (!mounted) return;
            ScaffoldMessenger.of(context).showSnackBar(
              SnackBar(content: Text('删除失败: ${e.toString()}')),
            );
          }
        }
      },
      child: Card(
        margin: const EdgeInsets.only(bottom: 16),
        shape: RoundedRectangleBorder(
          borderRadius: BorderRadius.circular(16),
          side: BorderSide(
            color: Colors.grey.withOpacity(0.2),
            width: 1,
          ),
        ),
        elevation: 0,
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            Padding(
              padding: const EdgeInsets.all(16),
              child: IntrinsicHeight(
                child: Row(
                  children: [
                    // 主要内容
                    Expanded(
                      child: Column(
                        crossAxisAlignment: CrossAxisAlignment.start,
                        children: [
                          Text(
                            thought.thought,
                            style: GoogleFonts.zcoolKuaiLe(
                              fontSize: 16,
                              color: AppColors.textPrimary,
                            ),
                            maxLines: 2,
                            overflow: TextOverflow.ellipsis,
                          ),
                          const SizedBox(height: 8),
                          Text(
                            _formatDate(thought.timestamp),
                            style: GoogleFonts.zcoolKuaiLe(
                              fontSize: 14,
                              color: Colors.grey,
                            ),
                          ),
                          const SizedBox(height: 8),
                          if (thought.distortionLabels.isNotEmpty) ...[
                            Wrap(
                              spacing: 8,
                              runSpacing: 8,
                              children: thought.distortionLabels.map((label) {
                                final color = labelColors[label] ?? Colors.grey[300];
                                return Container(
                                  padding: const EdgeInsets.symmetric(horizontal: 8, vertical: 4),
                                  decoration: BoxDecoration(
                                    color: color?.withOpacity(0.2),
                                    borderRadius: BorderRadius.circular(12),
                                    border: Border.all(
                                      color: color ?? Colors.grey,
                                      width: 1,
                                    ),
                                  ),
                                  child: Text(
                                    label,
                                    style: GoogleFonts.zcoolKuaiLe(
                                      fontSize: 12,
                                      color: color?.withOpacity(0.8),
                                    ),
                                  ),
                                );
                              }).toList(),
                            ),
                            const SizedBox(height: 8),
                          ],
                          if (thought.positiveThought != null && thought.positiveThought!.isNotEmpty) ...[
                            Row(
                              children: [
                                HeroIcon(
                                  HeroIcons.lightBulb,
                                  style: HeroIconStyle.solid,
                                  size: 16,
                                  color: Colors.yellow[700],
                                ),
                                const SizedBox(width: 8),
                                Expanded(
                                  child: Text(
                                    thought.positiveThought!,
                                    style: GoogleFonts.zcoolKuaiLe(
                                      fontSize: 14,
                                      color: Colors.yellow[800],
                                      height: 1.5,
                                    ),
                                    maxLines: 2,
                                    overflow: TextOverflow.ellipsis,
                                  ),
                                ),
                              ],
                            ),
                          ],
                        ],
                      ),
                    ),
                    // 右侧箭头
                    Center(
                      child: Padding(
                        padding: const EdgeInsets.only(left: 12),
                        child: const HeroIcon(
                          HeroIcons.chevronRight,
                          style: HeroIconStyle.solid,
                          size: 20,
                          color: Colors.grey,
                        ),
                      ),
                    ),
                  ],
                ),
              ),
            ),
          ],
        ),
      ),
    );
  }

  String _formatDate(DateTime date) {
    return '${date.year}-${date.month.toString().padLeft(2, '0')}-${date.day.toString().padLeft(2, '0')}';
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: Colors.white,
      appBar: AppBar(
        backgroundColor: Colors.white,
        elevation: 0,
        title: Text(
          '重塑记录',
          style: GoogleFonts.zcoolKuaiLe(
            fontSize: 20,
            fontWeight: FontWeight.bold,
          ),
        ),
        centerTitle: true,
        leading: IconButton(
          icon: Icon(Icons.arrow_back, color: AppColors.textPrimary),
          onPressed: () {
            Navigator.of(context).pushAndRemoveUntil(
              MaterialPageRoute(
                builder: (context) => const HomeScreen(),
              ),
              (route) => false,
            );
          },
        ),
      ),
      body: _isLoading
          ? const Center(child: CircularProgressIndicator())
          : _thoughts.isEmpty
              ? const Center(child: Text('暂无想法记录'))
              : RefreshIndicator(
                  onRefresh: _loadThoughts,
                  child: ListView.builder(
                    padding: const EdgeInsets.all(24),
                    itemCount: _thoughts.length,
                    itemBuilder: (context, index) => _buildThoughtCard(_thoughts[index]),
                  ),
                ),
      floatingActionButton: FloatingActionButton(
        onPressed: () {
          Navigator.pushReplacement(
            context,
            MaterialPageRoute(
              builder: (context) => const NewThoughtScreen(),
            ),
          );
        },
        backgroundColor: AppColors.primary,
        child: const HeroIcon(
          HeroIcons.plus,
          style: HeroIconStyle.solid,
          color: Colors.white,
        ),
      ),
    );
  }
} 